package filex

import (
	"bytes"
	"html/template"
	"os"
	"path/filepath"
	"strings"

	"gitcode.com/goinit/goinit/internal/pkg/dirx"
	"gitcode.com/goinit/goinit/internal/pkg/funcs"
)

func Create(filePath, content string, value interface{}) error {
	basePath := filepath.Dir(filePath)
	dirx.Create(basePath)

	file, err := os.Create(filePath)
	if err != nil {
		return err
	}
	defer file.Close()

	t := template.New(filePath).Funcs(funcs.Map)
	t.Parse(content)

	buf := new(bytes.Buffer)
	if err = t.Execute(buf, value); err != nil {
		return err
	}

	defer buf.Reset()

	text := buf.String()
	text = strings.ReplaceAll(text, "&lt;", "<")
	text = strings.ReplaceAll(text, "&gt;", ">")
	file.WriteString(text)
	return nil
}
